<?php

namespace app\admin\controller\shopro\commission;

use addons\shopro\service\commission\Agent as AgentService;
use app\admin\controller\shopro\Common;
use app\admin\model\Admin;
use app\admin\model\DailyPerformance;
use app\admin\model\shopro\commission\Log as LogModel;
use app\admin\model\shopro\order\Order;
use app\admin\model\shopro\order\OrderItem;
use app\admin\model\shopro\user\WalletLog;
use app\admin\model\User;
use think\Db;

//每日业绩
class Daily extends Common
{
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new DailyPerformance();
    }

    /**
     * 查看
     */
    /*public function index()
    {
        if (!$this->request->isAjax()) {
            $exportConfig = (new \addons\shopro\library\Export())->getConfig();
            $this->assignconfig("save_type", $exportConfig['save_type'] ?? 'download');
            return $this->view->fetch();
        }
        $search=$this->request->param("search");
        $search=json_decode($search,true);
        $today=true;
        if(isset($search["createtime"])){
            $time=explode(" - ",$search["createtime"][0]);
            $now=strtotime(date("Y-m-d",time()));
            $time0=strtotime($time[0]);
            $time1=strtotime($time[1]);
            $time0=strtotime(date("Y-m-d",$time0));
            $time1=strtotime(date("Y-m-d",$time1));
            if($now!=$time0 && $now!=$time1){
                $today=false;
            }
        }
        $list = $this->model;
        $count = $this->model;
        $listRows=$this->request->param("list_rows")??10;
        $page=$this->request->param("page")??1;
        if($page>1){
            $today=false;
        }
        if($today){
            $order = Order::field("sum(goods_old_amount) retail,sum(pay_fee) payment,sum(pv_price) pv_price,sum(goods_amount) paygoods_price,sum(dispatch_amount) freight,sum(total_discount_fee) total_discount_fee")
                ->whereTime("createtime", "today")->whereIn("status",["paid","completed"])->find();
            //留存-向平台进货的金额-每笔订单pv值*3%-平台给出平级奖(新增 +每笔订单零售价-pv值)(新增 -每笔订单pv值*5)
            $wallet= WalletLog::where(["type" => "money", "event" => "money_payment","flow_id"=>0])
                ->where("amount<0")
                ->whereTime("createtime", "today")->sum("amount");//向平台进货金额
            $equal = WalletLog::where(["type" => "money", "event" => "money_payment_cut_income", "flow_id" => 0])
                ->where("amount>0")
                ->whereTime("createtime", "today")->sum("amount");//平台给出平级奖
            $pv_price=$order["pv_price"]??0;
            $price = bcmul($pv_price, 0.03, 2);
            $individuality_price = bcmul($pv_price, 0.05, 2);
            $retail = $order["retail"] ?? 0;
            $payment = $order["payment"] ?? 0;
            $retained = $wallet ?? 0;
            $paygoods_price=$order["paygoods_price"]??0;
            $freight=$order["freight"]??0;
            $total_discount_fee = $order["total_discount_fee"] ?? 0;
            $retained = bcsub(abs($retained), (bcadd($price, $equal,2)), 2);
            $retained=bcadd($retained,(bcsub($retail, $pv_price,2)),2);//(新增 +每笔订单零售价-pv值)
            $retained = bcsub($retained, $individuality_price, 2);//(新增 -每笔订单pv值*5)
            $q_time = strtotime(date("Y-m-d", strtotime("-1 days", time())));//昨天时间
            $order = new Order();
            $item = OrderItem::where('order_id=' . $order->getTable() . '.id')->fetchSql()
                //->whereBetween("updatetime", [$q_time, strtotime(date("Y-m-d",  time()))])
                ->whereTime("updatetime","today")
                ->where('refund_status', '=', 2)->column("order_id");
            $return_order = Order::field("sum(goods_old_amount) retail,sum(pay_fee) payment")
                ->whereIn("status", ['paid', 'completed'])
                ->where("EXISTS (" . $item . ")")->find();//昨天退款
            $return_retail = $return_order["retail"] ?? 0;//昨天退款原价
            $return_payment = $return_order["payment"] ?? 0;//昨天退款支付金额
            if (!empty($return_order)) {
                $retail = bcsub($retail, $return_retail, 2);
                $payment = bcsub($payment, $return_payment, 2);
            }
            $sql="(select 0 id,".$retail." retail,".$payment." payment,".$retained." retained,'".date("Y-m-d",time())."' createtime,0 yesterday_cut_retail,0 yesterday_cut_payment,0 yesterday_cut_retained,
            ".((abs($wallet))??0)." pc_paygoods,".($equal??0)." pc_equal,".($price??0)." pc_bonus,".($individuality_price??0)." pc_individual,".$pv_price." pv_price,"
                .$paygoods_price." paygoods_price,".$freight." freight,".$total_discount_fee." total_discount_fee)";
            $list = $list->union($sql,true);
            $count = $count->union($sql,true);
        }
        dump($list);die();
        if($this->request->param("search") && !empty($this->request->param("search"))){
            $serch=json_decode($this->request->param("search"),true);
            if(!empty($serch)){
                $createtime = explode(' - ', $serch["createtime"][0]);
                $list=$list->whereBetween('createtime', [strtotime($createtime[0]),strtotime($createtime[1])]);
                $count=$count->whereBetween('createtime', [strtotime($createtime[0]),strtotime($createtime[1])]);
            }
        }
        $list=$list
            ->order("createtime desc,id desc")->fetchsql()
            ->limit((($page - 1) * $listRows), $listRows)->select();
        dump($list);die();
        $count=Db::query("select count(1) num from (".$count->fetchsql()->select().") all_count");
        $total=$count[0]["num"]??1;
        $lastPage=(int) ceil($total / $listRows);
        $money=$this->model->field("sum(retail) retail,sum(payment) payment,sum(retained) retained")->find();
        $retail=bcadd(($money["retail"]??0),($list[0]["retail"]??0),2);
        $payment=bcadd(($money["payment"]??0),($list[0]["payment"]??0),2);
        $retained=bcadd(($money["retained"]??0),($list[0]["retained"]??0),2);
        $data=[
            "data"=>$list,
            "total"=>$total,
            "lastPage"=>$lastPage,
            "retail"=>$retail,
            "payment"=>$payment,
            "retained"=>$retained,
            //"hasMore"=>$this->currentPage < $lastPage
        ];
        $this->success('获取成功', null, $data);
    }*/
    /**
     * 查看
     */
    public function index()
    {
        if (!$this->request->isAjax()) {
            $exportConfig = (new \addons\shopro\library\Export())->getConfig();
            $this->assignconfig("save_type", $exportConfig['save_type'] ?? 'download');
            return $this->view->fetch();
        }
        $list = $this->model;
        $today=$this->model->whereTime("createtime","today")->find();
        $order = Order::field("sum(goods_old_amount) retail,sum(pay_fee) payment,sum(pv_price) pv_price,sum(goods_amount) paygoods_price,sum(dispatch_amount) freight,sum(total_discount_fee) total_discount_fee")
            ->whereTime("createtime", "today")->whereIn("status",["paid","completed"])->find();
        //留存-向平台进货的金额-每笔订单pv值*3%-平台给出平级奖(新增 +每笔订单零售价-pv值)(新增 -每笔订单pv值*5)
        $wallet= WalletLog::where(["type" => "money", "event" => "money_payment","flow_id"=>0])
            ->where("amount<0")
            ->whereTime("createtime", "today")->sum("amount");//向平台进货金额
        $equal = WalletLog::where(["type" => "money", "event" => "money_payment_cut_income", "flow_id" => 0])
            ->where("amount>0")
            ->whereTime("createtime", "today")->sum("amount");//平台给出平级奖
        $pv_price=$order["pv_price"]??0;
        $price = bcmul($pv_price, 0.03, 2);
        $individuality_price = bcmul($pv_price, 0.05, 2);
        $retail = $order["retail"] ?? 0;
        $payment = $order["payment"] ?? 0;
        $retained = $wallet ?? 0;
        $paygoods_price=$order["paygoods_price"]??0;
        $freight=$order["freight"]??0;
        $total_discount_fee = $order["total_discount_fee"] ?? 0;
        $retained = bcsub(abs($retained), (bcadd($price, $equal,2)), 2);
        $retained=bcadd($retained,(bcsub($retail, $pv_price,2)),2);//(新增 +每笔订单零售价-pv值)
        $retained = bcsub($retained, $individuality_price, 2);//(新增 -每笔订单pv值*5)
        $order = new Order();
        $item = OrderItem::where('order_id=' . $order->getTable() . '.id')->fetchSql()
            ->whereTime("updatetime","today")
            ->where('refund_status', '=', 2)->column("order_id");
        $return_order = Order::field("sum(goods_old_amount) retail,sum(pay_fee) payment")
            ->whereIn("status", ['paid', 'completed'])
            ->where("EXISTS (" . $item . ")")->find();//昨天退款
        $return_retail = $return_order["retail"] ?? 0;//昨天退款原价
        $return_payment = $return_order["payment"] ?? 0;//昨天退款支付金额
        if (!empty($return_order)) {
            $retail = bcsub($retail, $return_retail, 2);
            $payment = bcsub($payment, $return_payment, 2);
        }
        if(!empty($today)){
            $today->save([
                "retail" => $retail,
                "payment" => $payment,
                "retained" => $retained,
                "yesterday_cut_retail" => $return_order["retail"]  ?? 0,//昨天退款扣除总零售额
                "yesterday_cut_payment" => $return_order["payment"] ?? 0,//昨天退款扣除总支付额
                "yesterday_cut_retained" => 0,//昨天扣除总留存
                "createtime" =>strtotime(date("Y-m-d",time())),
                "pc_paygoods" => (abs($wallet))??0,
                "pc_equal" => $equal??0,
                "pc_bonus" => $price??0,
                "pc_individual" => $individuality_price??0,
                "pv_price" =>$pv_price,
                "paygoods_price" =>$paygoods_price,
                "freight" =>$freight,
                "total_discount_fee" =>$total_discount_fee,
            ]);
        }else{
            $this->model->save([
                "retail" => $retail,
                "payment" => $payment,
                "retained" => $retained,
                "yesterday_cut_retail" => $return_order["retail"]  ?? 0,//昨天退款扣除总零售额
                "yesterday_cut_payment" => $return_order["payment"] ?? 0,//昨天退款扣除总支付额
                "yesterday_cut_retained" => 0,//昨天扣除总留存
                "createtime" =>strtotime(date("Y-m-d",time())),
                "pc_paygoods" => (abs($wallet))??0,
                "pc_equal" => $equal??0,
                "pc_bonus" => $price??0,
                "pc_individual" => $individuality_price??0,
                "pv_price" =>$pv_price,
                "paygoods_price" =>$paygoods_price,
                "freight" =>$freight,
                "total_discount_fee" =>$total_discount_fee,
            ]);
        }
        if($this->request->param("search") && !empty($this->request->param("search"))){
            $serch=json_decode($this->request->param("search"),true);
            if(!empty($serch)){
                $createtime = explode(' - ', $serch["createtime"][0]);
                $list=$list->whereBetween('createtime', [strtotime($createtime[0]),strtotime($createtime[1])]);
            }
        }
        $list=$list->field("*,from_unixtime(createtime, '%Y-%m-%d') createtime")
            ->order("createtime desc,id desc")->paginate($this->request->param('list_rows', 10));
        $money=$this->model->field("sum(retail) retail,sum(payment) payment,sum(retained) retained")->find();
        $data=[
            "data"=>$list,
            "retail"=>$money["retail"].""??0,
            "payment"=>$money["payment"].""??0,
            "retained"=>$money["retained"].""??0,
        ];
        $this->success('获取成功', null, $data);
    }
    /**
     * 导出
     * */
    public function export()
    {
        $cellTitles = [
            // 订单表字段
            'id' => 'ID',
            'retail' => '总零售额',
            'payment' => '总支付额',
            'pv_price' => '总pv',
            'retained' => '总留存',
            'pc_paygoods' => '向平台进货货款',
            'pc_equal' => '平台发放平级奖',
            'pc_bonus' => '订单pv3%',
            'pc_individual' => '个体户5%',
            'createtime' => '创建时间',
        ];

        $list = $this->model;
        $today=$this->model->whereTime("createtime","today")->find();
        $order = Order::field("sum(goods_old_amount) retail,sum(pay_fee) payment,sum(pv_price) pv_price,sum(goods_amount) paygoods_price,sum(dispatch_amount) freight,sum(total_discount_fee) total_discount_fee")
            ->whereTime("createtime", "today")->whereIn("status",["paid","completed"])->find();
        //留存-向平台进货的金额-每笔订单pv值*3%-平台给出平级奖(新增 +每笔订单零售价-pv值)(新增 -每笔订单pv值*5)
        $wallet= WalletLog::where(["type" => "money", "event" => "money_payment","flow_id"=>0])
            ->where("amount<0")
            ->whereTime("createtime", "today")->sum("amount");//向平台进货金额
        $equal = WalletLog::where(["type" => "money", "event" => "money_payment_cut_income", "flow_id" => 0])
            ->where("amount>0")
            ->whereTime("createtime", "today")->sum("amount");//平台给出平级奖
        $pv_price=$order["pv_price"]??0;
        $price = bcmul($pv_price, 0.03, 2);
        $individuality_price = bcmul($pv_price, 0.05, 2);
        $retail = $order["retail"] ?? 0;
        $payment = $order["payment"] ?? 0;
        $retained = $wallet ?? 0;
        $paygoods_price=$order["paygoods_price"]??0;
        $freight=$order["freight"]??0;
        $total_discount_fee = $order["total_discount_fee"] ?? 0;
        $retained = bcsub(abs($retained), (bcadd($price, $equal,2)), 2);
        $retained=bcadd($retained,(bcsub($retail, $pv_price,2)),2);//(新增 +每笔订单零售价-pv值)
        $retained = bcsub($retained, $individuality_price, 2);//(新增 -每笔订单pv值*5)
        $order = new Order();
        $item = OrderItem::where('order_id=' . $order->getTable() . '.id')->fetchSql()
            ->whereTime("updatetime","today")
            ->where('refund_status', '=', 2)->column("order_id");
        $return_order = Order::field("sum(goods_old_amount) retail,sum(pay_fee) payment")
            ->whereIn("status", ['paid', 'completed'])
            ->where("EXISTS (" . $item . ")")->find();//昨天退款
        $return_retail = $return_order["retail"] ?? 0;//昨天退款原价
        $return_payment = $return_order["payment"] ?? 0;//昨天退款支付金额
        if (!empty($return_order)) {
            $retail = bcsub($retail, $return_retail, 2);
            $payment = bcsub($payment, $return_payment, 2);
        }
        if(!empty($today)){
            $today->save([
                "retail" => $retail,
                "payment" => $payment,
                "retained" => $retained,
                "yesterday_cut_retail" => $return_order["retail"]  ?? 0,//昨天退款扣除总零售额
                "yesterday_cut_payment" => $return_order["payment"] ?? 0,//昨天退款扣除总支付额
                "yesterday_cut_retained" => 0,//昨天扣除总留存
                "createtime" =>strtotime(date("Y-m-d",time())),
                "pc_paygoods" => (abs($wallet))??0,
                "pc_equal" => $equal??0,
                "pc_bonus" => $price??0,
                "pc_individual" => $individuality_price??0,
                "pv_price" =>$pv_price,
                "paygoods_price" =>$paygoods_price,
                "freight" =>$freight,
                "total_discount_fee" =>$total_discount_fee,
            ]);
        }else{
            $this->model->save([
                "retail" => $retail,
                "payment" => $payment,
                "retained" => $retained,
                "yesterday_cut_retail" => $return_order["retail"]  ?? 0,//昨天退款扣除总零售额
                "yesterday_cut_payment" => $return_order["payment"] ?? 0,//昨天退款扣除总支付额
                "yesterday_cut_retained" => 0,//昨天扣除总留存
                "createtime" =>strtotime(date("Y-m-d",time())),
                "pc_paygoods" => (abs($wallet))??0,
                "pc_equal" => $equal??0,
                "pc_bonus" => $price??0,
                "pc_individual" => $individuality_price??0,
                "pv_price" =>$pv_price,
                "paygoods_price" =>$paygoods_price,
                "freight" =>$freight,
                "total_discount_fee" =>$total_discount_fee,
            ]);
        }
        $total=$this->model->count();
        // 数据总条数
        if ($total <= 0) {
            $this->error('导出数据为空');
        }
        $export = new \addons\shopro\library\Export();
        $params = [
            'file_name' => '每日业绩明细列表',
            'cell_titles' => $cellTitles,
            'total' => $total,
            'is_sub_cell' => false,
        ];
        $result = $export->export($params, function ($pages) use ($list, $total) {
            if($this->request->param("search") && !empty($this->request->param("search"))){
                $serch=json_decode($this->request->param("search"),true);
                if(!empty($serch)){
                    $createtime = explode(' - ', $serch["createtime"][0]);
                    $list=$list->whereBetween('createtime', [strtotime($createtime[0]),strtotime($createtime[1])]);
                }
            }
            $list=$list->field("*,from_unixtime(createtime, '%Y-%m-%d') createtime")
                ->order("createtime desc,id desc")
                ->limit((($pages['page'] - 1) * $pages['list_rows']), $pages['list_rows'])
                ->select();
            $newDatas = [];
            foreach ($list as &$item) {
                $data = [
                    // 订单表字段
                    'id' => $item['id'],
                    'retail' =>$item["retail"],
                    'payment' =>$item["payment"],
                    'pv_price' =>$item["pv_price"],
                    'retained' =>$item["retained"],
                    'pc_paygoods' =>$item["pc_paygoods"],
                    'pc_equal' =>$item["pc_equal"],
                    'pc_bonus' =>$item["pc_bonus"],
                    'pc_individual' =>$item["pc_individual"],
                    'createtime' =>$item["createtime"],
                ];
                $newDatas[] = $data;
            }
            return $newDatas;
        });

        $this->success('导出成功' . (isset($result['file_path']) && $result['file_path'] ? '，请在服务器: “' . $result['file_path'] . '” 查看' : ''), null, $result);
    }
}
